package com.example.demo.controller;

import com.example.demo.annotation.UserLoginToken;
import com.example.demo.common.enums.CustomizeEnum;
import com.example.demo.entity.User;
import com.example.demo.service.impl.LoginService;
import com.example.demo.service.impl.UserServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.validation.Valid;
import java.util.HashMap;

/**
 * @Author: ak
 * @Date: 2020/3/30 13:42
 */
@Controller
@Slf4j
public class LoginController {
    @Autowired
    LoginService loginService;
    @Autowired
    UserServiceImpl userService;

    /**
     * 登录页面路由
     */
    @GetMapping("login")
    public String login(){
        return "login";
    }

    /**
     * 登录页面功能实现
     */
    @PostMapping("login")
    public String login(User user, Model model) {
        //如果已经登录，则直接跳转个人中心
        if (SecurityUtils.getSubject().getPrincipal()!=null){
            model.addAttribute("user",user);
            model.addAttribute("msg","请不要重复登录!");
            return "home";
        }
        CustomizeEnum loginMsg = loginService.userLogin(user.getUUsername(), user.getUPassword());
        if (loginMsg.equals(CustomizeEnum.LOGIN_USER) || loginMsg.equals(CustomizeEnum.LOGIN_ADMIN)){
            model.addAttribute("msg",loginMsg.getMsg());
            model.addAttribute("user",user);
            log.info("用户"+user.getUUsername()+loginMsg.getMsg());
            return "home";
        }
        log.info("用户"+user.getUUsername()+loginMsg.getMsg());
        model.addAttribute("msg",loginMsg.getMsg());
        return "login";
    }

    /**
     * 注册页面路由
     */
    @GetMapping("register")
    public String register(){
        return "register";
    }

    /**
     * 注册页面功能实现
     */
    @PostMapping("register")
    public ModelAndView register(@Valid User user, BindingResult result){
        ModelAndView modelAndView = new ModelAndView();
        CustomizeEnum registerMsg = loginService.register(user.getUUsername(), user.getUPassword(), user.getUPassword2());
        //字段判断
        if (result.hasErrors()){
            modelAndView.addObject("msg",result.getFieldError().getDefaultMessage());
            modelAndView.setViewName("register");
            return modelAndView;
        }
        //shiro拦截
        if (!registerMsg.equals(CustomizeEnum.REGISTER_SUCCESS)){
            modelAndView.addObject("msg",registerMsg.getMsg());
            modelAndView.setViewName("register");
            return modelAndView;
        }
        log.info("用户"+user.getUUsername()+registerMsg.getMsg());
        modelAndView.addObject("msg",registerMsg.getMsg());
        modelAndView.setViewName("home");
        return modelAndView;
    }

    /**
     * 无权限访问路由跳转
     */
    @GetMapping("unPerms")
    public String unPerms(Model model){
        model.addAttribute("msg","无权限操作");
        log.error("用户无权限");
        return "index";
    }

    @GetMapping("/auth/logout")
    public String logOut(Model model){
        model.addAttribute("msg","退出成功");
        User user = (User)SecurityUtils.getSubject().getPrincipal();
        log.error("用户{}退出成功",user.getUUsername());
        return "index";
    }

    /**
     * JWT登录
     */
    @PostMapping("/JWTLogin")
    @ResponseBody
    public Object login(@RequestBody User user) {
        HashMap<Object, Object> jsonObject = new HashMap<>(16);
        User userForBase=userService.getUserByName(user.getUUsername());
        if(userForBase==null){
            jsonObject.put("message","登录失败,用户不存在");
            return jsonObject;
        }else {
            if (!userForBase.getUUsername().equals(user.getUPassword())){
                jsonObject.put("message","登录失败,密码错误");
                return jsonObject;
            }else {
                String token = userForBase.getToken(userForBase);
                jsonObject.put("token", token);
                jsonObject.put("user", userForBase);
                return jsonObject;
            }
        }
    }

    @UserLoginToken
    @GetMapping("/getMessage")
    @ResponseBody
    public String getMessage(){
        return "你已通过验证";
    }
}
